package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.GenericData;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.po.MarketStorage;
import com.cskaoyan.constant.Constant;
import com.cskaoyan.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author LiangRuiJiang
 * @since 2022/06/05  19:21
 */
@RestController
@RequestMapping("admin/storage")
public class StorageController {

    @Autowired
    StorageService storageService;

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public BaseRespVo create(MultipartFile file, HttpServletRequest request) throws IOException {
        MarketStorage marketStorage = storageService.createFile(file, request);
        File fileUpload = new File(Constant.FILE_STORAGE_ADRESS, marketStorage.getKey());
        file.transferTo(fileUpload);
        return BaseRespVo.ok(marketStorage);
    }

    @RequestMapping(value = "list")
    public BaseRespVo list(BaseParam param, String key, String name) throws IOException {

        GenericData<MarketStorage> marketStorage = storageService.queryStorage(param, key, name);
        return BaseRespVo.ok(marketStorage);
    }

    @RequestMapping("update")
    public BaseRespVo update(@RequestBody() MarketStorage marketStorage){
        marketStorage = storageService.updateStorage(marketStorage);
        return BaseRespVo.ok(marketStorage);
    }

    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody() MarketStorage marketStorage){
        storageService.deleteStorage(marketStorage);
        return BaseRespVo.ok();
    }
}
